<?php

namespace App\Http\Controllers\Shop;

use App\Http\Resources\Shop\Withdraw as WithdrawResource;
use App\Http\Resources\Shop\WithdrawCollection;
use App\Http\Controllers\ApiController;
use App\Models\ShopBalanceLog;
use Illuminate\Http\Request;
use App\Models\Withdraw;
use App\Models\Shop;
use Auth;
use DB;

class WithdrawController extends ApiController
{
    /**
     * 提现列表.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $limit = $request->input('size');
        $date = $request->input('date');
        $invoice = $request->input('invoice');
        $status = $request->input('status');

        $orm = Withdraw::OwnerShop()->orderBy('created_at', 'DESC');

        $status && $orm->where('status', $status);
        $invoice && $orm->where('invoice', $invoice);

        if($date) {
            if($date[0] && time($date[0])) {
                $orm->where('created_at', '>', $date[0]);
            }

            if($date[1] && time($date[1])) {
                $orm->where('created_at', '<', $date[1]);
            }
        }

        return (new WithdrawCollection($orm->paginate($limit)))
            ->additional(['meta' => [
                'balance' => Auth::guard('shop')->user()->balance,
            ]]);

    }

    /**
     * 提现
     *
     * @return \Illuminate\Http\Response
     */
    public function cash(Request $request)
    {
        $amount = $request->input('amount', 0);
        $bankCardNumber = $request->input('bank_card_number', 0);
        
        if(!is_numeric($amount) || $amount <= 0) {
            return $this->failed('提现金额无效');
        }

        $shop = Auth::guard('shop')->user();
        $amount = floatval(number_format($amount, 2, '.', '')); // 提现金额

        $bankCardNumber = $shop->user->bank_card; // 银行卡

        if (empty($bankCardNumber)) {
            return $this->failed('请先绑定银行卡');
        }

        if ($amount > $shop->balance) {
            return $this->failed('请输入正确的提现金额');
        }

        DB::beginTransaction();

        // 记录提现
        $withdrawOrm = new Withdraw();
        $withdrawOrm->shop_id = $shop->id;
        $withdrawOrm->amount = $amount;
        $withdrawOrm->bank_card_number = $bankCardNumber;
        $withdrawOrm->status = Withdraw::STATUS_PROCESSING;
        $withdrawOrm->remark = '商家提现';
        $withdrawOrm->save();

        // 记录财务明细，日后再说
        $balanceLogOrm = new ShopBalanceLog();
        $balanceLogOrm->shop_id = $shop->id;
        $balanceLogOrm->count = (0 - $amount);
        $balanceLogOrm->balance = $shop->balance - $amount;
        $balanceLogOrm->invoice = $withdrawOrm->invoice;
        $balanceLogOrm->type = ShopBalanceLog::TYPE_WITHDRAW; // 标志为提现
        $balanceLogOrm->remark = '提现';
        $balanceLogOrm->save();

        // 扣除余额
        $shop->decrement('balance', $amount);

        DB::commit();
        return $this->message('提现成功');
    }
}
